package cn.suchan.sharedelectrombile.controller;

import cn.suchan.sharedelectrombile.response.Response;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.ArrayList;
import java.util.List;

@Controller
public class AppController {
    @GetMapping("/")
    public String home(){
        return "index.html";
    }

    public List<Response> validResult(BindingResult bindingResult){
        List<Response> responseList = new ArrayList<>();
        for (ObjectError error : bindingResult.getAllErrors()){
            Response rs = new Response();
            System.out.println(error.getDefaultMessage());
            rs.setCode(error.getCode());
            rs.setMsg(error.getDefaultMessage());
            rs.setData(null);
            responseList.add(rs);
        }
        return responseList;
    }

    public List<Response> saveAndDeleteValid(BindingResult bindingResult,boolean isTrue){
        List<Response> responseList = new ArrayList<>();
        if (bindingResult.hasErrors()){
            responseList = validResult(bindingResult);
        }else{
            Response rs = new Response();
            if (isTrue){
                rs.setCode("Success");
                rs.setMsg("请求成功");
                rs.setData(null);
            }else {
                rs.setCode("Fail");
                rs.setMsg("请求失败");
                rs.setData(null);
            }
            responseList.add(rs);
        }
        return responseList;
    }
}
